package com.example.tcp;

import com.example.codec.BootstrapConfig;
import com.example.tcp.reciver.MessageReciver;
import com.example.tcp.redis.RedisManager;
import com.example.tcp.register.RegistryZK;
import com.example.tcp.register.ZKit;
import com.example.tcp.server.LimServer;
import com.example.tcp.server.LimWebSocketServer;
import com.example.tcp.utils.MqFactory;
import org.I0Itec.zkclient.ZkClient;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;

public class Starter {
    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        //进行获取配置文件的路径
        String path = Starter.class.getClassLoader().getResource("").getPath()+"config.yml";
        String decode = URLDecoder.decode(path, "UTF-8");   //有乱码的情况所以使用这个解决路径乱码的情况
        start(decode);
    }


    public static void start(String path){
        try{
            Yaml yaml=new Yaml();
            FileInputStream fileInputStream = new FileInputStream(path);
            BootstrapConfig bootstrapConfig = yaml.loadAs(fileInputStream, BootstrapConfig.class);

            new LimServer(bootstrapConfig.getLim()).start();                 //tcp       服务的初始化
            new LimWebSocketServer(bootstrapConfig.getLim()).start();        //websocket 服务的初始化
            //redisson 客户端相关的初始化的内容  //这里读取的是 resources 里面的 config.yml
            RedisManager.init(bootstrapConfig);
            MqFactory.init(bootstrapConfig.getLim().getRabbitmq());      //对mq的初始化
            MessageReciver.init(bootstrapConfig.getLim().getBrokerId()+"");           //对消息的监听
            registerZK(bootstrapConfig);                  //对zookeeper 服务的注册和使用
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static  void registerZK(BootstrapConfig config) throws UnknownHostException {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();     //获取 ip
        //这里有个奇怪的现象使加上过期时间就连不上  ，不加就连的上
        ZkClient zkClient = new ZkClient(config.getLim().getZkConfig().getZkAddr());
        ZKit zKit = new ZKit(zkClient);
        RegistryZK registryZK = new RegistryZK(zKit, hostAddress, config.getLim());
        Thread thread = new Thread(registryZK);
        thread.start();
    }
}
